<template>
  <el-dialog :visible.sync="formVisible" center width="783" class="warehouse_add_dialog" @close="handleCancel">
    <div slot="title" class="header_title_box">
      <h2>{{ type === 0 ? '新建仓库' : '编辑仓库' }}</h2>
    </div>
    <el-form :ref="formName" :model="formFieldsData" :rules="formRules" label-width="130px">
      <el-row :gutter="59">
        <el-col :span="12">
          <el-form-item label="仓库名称" prop="name">
            <el-input v-model="formFieldsData.name" placeholder="请输入仓库名称" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="仓库代码" prop="code">
            <el-input v-model="formFieldsData.code" :disabled="type === 1" placeholder="请输入仓库代码" />
          </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item label="仓库类型" prop="type">
            <el-select v-model="formFieldsData.type" clearable placeholder="-请选择-" class="wfull" @change="changeTypeHandler">
              <el-option v-for="item in warehouseTypes" :key="item.id" :value="item.id" :label="item.name" :disabled="item.id === 4 && FBAWarehouses.length > 0" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="上级仓库" :prop="isFirstLevel ? 'parent_id_no_required' : 'parent_id'" :show-message="!isFirstLevel">
            <el-select v-model="formFieldsData.parent_id" clearable filterable placeholder="-请选择-" class="wfull" :disabled="isFirstLevel" @change="changeWarehouseHandler">
              <el-option v-for="item in warehouseList" :key="item.id" :value="item.id" :label="item.name" :disabled="item.is_active==1?false:true" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属客户" :prop="formFieldsData.department_id?'company_id_no_required':(isFirstLevel ? 'company_id_no_required' : 'company_id')" :show-message="!isFirstLevel">
            <el-select v-model="formFieldsData.company_id" clearable filterable placeholder="-请选择-" class="wfull" :disabled="formFieldsData.department_id?true:isFirstLevel" @change="changeCompanyHandler">
              <el-option v-for="item in companyList" :key="item.id" :value="item.id" :label="item.name" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属组织" :prop="formFieldsData.company_id?'department_id_no_required':(isFirstLevel ? 'department_id_no_required' : 'department_id')" :show-message="!isFirstLevel">
            <el-cascader v-model="department" placeholder="-请选择-" :options="departments" :props="{ checkStrictly: true }" :disabled="formFieldsData.company_id?true:isFirstLevel" class="wfull" @change="departmentHandler" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="州/省" prop="state">
            <el-select v-model="formFieldsData.state" clearable filterable placeholder="-请选择-" :disabled="!isFirstLevel" class="wfull" @change="changeStateHandler">
              <el-option v-for="item in statesList" :key="item.id" :label="`${item.code}(${item.cname})`" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="城市" prop="city">
            <el-select v-model="formFieldsData.city" clearable filterable placeholder="-请选择-" :disabled="!isFirstLevel" class="wfull" @change="changeCityHandler">
              <el-option v-for="item in cityList" :key="item.id" :label="`${item.name}(${item.cname})(${item.code})`" :value="item.lower_name" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="街道" prop="street">
            <el-input v-model="formFieldsData.street" placeholder="请输入街道" class="wfull" :disabled="!isFirstLevel" />
            <!-- <el-select v-model="formFieldsData.street" clearable placeholder="-请选择-" class="wfull" :disabled="!isFirstLevel">
              <el-option v-for="item in streetList" :key="item.id" :value="item.name" :label="item.name" />
            </el-select> -->
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="仓库邮编" prop="zipcode">
            <el-autocomplete v-model="formFieldsData.zipcode" :fetch-suggestions="queryZipCode" :disabled="!isFirstLevel" placeholder="请输入内容" class="wfull" />
            <!-- <el-select v-model="formFieldsData.zipcode" clearable filterable placeholder="-请选择-" class="wfull" :disabled="!isFirstLevel">
              <el-option v-for="item in cityCodeList" :key="item.id" :value="item.zip" :label="item.zip" />
            </el-select> -->
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否第三方仓库" prop="is_third_part">
            <!-- <el-select v-model="formFieldsData.is_third_part" clearable placeholder="-请选择-" class="wfull" :disabled="formFieldsData.is_third_part !== ''"> -->
            <el-select v-model="formFieldsData.is_third_part" clearable placeholder="-请选择-" class="wfull" :disabled="!isFirstLevel">
              <el-option :value="1" label="是" />
              <el-option :value="0" label="否" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注" prop="notes">
            <el-input v-model="formFieldsData.notes" placeholder="" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer">
      <el-button type="primary" :loading="btnLoading" @click="handleSubmitSelf">保存</el-button>
      <el-button @click="handleCancel">取消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { WAREHOUSE_TYPE } from '../../../utils/const'
import { validChineseOrs } from '../../../utils/validate'
import {
  statesList,
  cityList,
  streetList,
  cityPostalCode
} from '../../../utils/publicData.js' // 街道和城市
export default {
  name: 'WarehouseDialog',
  data() {
    return {
      formVisible: false,
      formName: 'warehouse', // 新增仓库formname
      formFieldsData: {
        id: '', // 仓库id
        name: '', // 仓库名称
        code: '', // 仓库编码
        type: '', // 仓库类型
        parent_id: '', // 上级仓库id
        company_id: '', // 所属客户id
        department_id: '', // 所属组织
        state: '', // 省/州
        city: '', // 城市
        street: '', // 街道
        zipcode: '', // 邮编
        notes: '', // 备注
        is_third_part: ''
      }, // 新增仓库formdata
      department: [], // 所属组织
      btnLoading: false,
      formRules: {
        name: [
          { required: true, message: '请输入仓库名称', trigger: 'blur' },
          { max: 50, message: '仓库名称须在50个字符以内', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入仓库编码', trigger: 'blur' },
          {
            validator(rule, value, callback) {
              if (validChineseOrs(value)) {
                callback(new Error('编码须是字母，数字，非空字符组成'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          },
          { max: 30, message: '仓库编码须在30个字符以内', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择仓库类型', trigger: 'change' }
        ],
        parent_id: [
          { required: true, message: '请选择上级仓库', trigger: 'change' }
        ],
        parent_id_no_required: [],
        company_id: [
          { required: true, message: '请选择所属客户', trigger: 'change' }
        ],
        company_id_no_required: [],
        department_id: [
          { required: true, message: '请选择所属组织', trigger: 'change' }
        ],
        department_id_no_required: [],
        state: [{ required: true, message: '请选择省/州', trigger: 'change' }],
        city: [{ required: true, message: '请选择城市', trigger: 'change' }],
        street: [{ max: 50, message: '街道必须在50个字符', trigger: 'blur' }],
        zipcode: [{ required: true, message: '请选择邮编', trigger: 'change' }],
        notes: [
          { max: 500, message: '备注须在500个字符以内', trigger: 'change' }
        ],
        is_third_part: [
          { required: true, message: '请选择是否第三方仓库', trigger: 'change' }
        ]
      }, // 新增仓库form rule
      warehouseTypes: WAREHOUSE_TYPE, // 仓库类型
      departments: [],
      warehouseList: [], // 上级仓库列表
      companyList: [], // 所属客户列表
      FBAWarehouses: [], // FBA仓库
      statesList: [], // 省/州列表
      cityList: [], // 城市列表
      streetList: [], // 街道列表
      cityCodeList: [], // 城市邮编列表
      type: 0 // 0 新增 1 编辑
    }
  },
  computed: {
    isFirstLevel() {
      // 一级仓库（实体仓，FBA仓）
      const vm = this
      return [1, 4].indexOf(vm.formFieldsData.type) > -1
    },
    selectCity() {
      return this.cityList.find(e => e.lower_name === this.formFieldsData.city)
    }
  },
  created() {
    const vm = this
    vm.getStatesList() // 获取省/州列表
  },
  methods: {
    // 搜索邮编
    queryZipCode(str, callback) {
      const vm = this
      const selectCity = this.cityList.find(e => e.lower_name === vm.formFieldsData.city)
      if (selectCity) {
        cityPostalCode(selectCity.id).then((res) => {
          const list = res.filter(e => e.zip.includes(str)).map(e => {
            e['value'] = e.zip
            return e
          })
          callback(list)
        })
      } else {
        setTimeout(() => {
          callback([])
        })
      }
    },
    /**
     * 修改仓库类型 handler
     */

    changeTypeHandler(e) {
      const vm = this
      if (vm.isFirstLevel) {
        // 实体仓，FBA仓不需要上级仓和租住
        vm.formFieldsData.parent_id = ''
        vm.formFieldsData.zipcode = ''
        vm.formFieldsData.state = ''
        vm.formFieldsData.city = ''
        vm.formFieldsData.street = ''
        vm.formFieldsData.department_id = ''
        vm.formFieldsData.company_id = ''
        vm.formFieldsData.is_third_part = ''
        vm.department = []
      }
    },
    /**
     * 获取组织列表
     * */

    getDepartmentList() {
      const vm = this
      const filter = (arr, parentIds = []) => {
        return arr.map((e) => {
          e['value'] = e.id
          e['label'] = e.department_name
          // ids 用于 后续的 级联回填
          const ids = parentIds.concat()
          ids.push(e.id)
          e['ids'] = ids
          if (e.children) {
            e.children = filter(e.children, ids.concat())
          }
          return e
        })
      }
      vm.$http.get('/departments').then((res) => {
        vm.departments = filter(res.data)
      })
    },
    /**
     * 获取上级仓库
     * */

    getWarehouseList() {
      const vm = this
      const params = {
        type: 1,
        page: 1,
        limit: 100000000
        // is_active: 1
      }
      vm.$http.get('/warehouse', { params }).then((res) => {
        let data = res.data
        // 如果是编辑并且是实体仓，则上级仓库列表去除掉自身
        if (vm.type === 1 && vm.formFieldsData.type === 1) {
          data = data.filter((e) => e.id !== vm.formFieldsData.id)
        }
        vm.warehouseList = data
      })
    },
    // 获取所属客户
    getCompanyList() {
      const vm = this
      const params = {
        type: 1,
        page: 1,
        limit: 100000000
        // is_active: 1
      }
      vm.$http.get('/company', { params }).then((res) => {
        console.log(res)
        vm.companyList = res.data
      })
    },

    /**
     * 获取FBA仓库
     * */
    getFBAWarehouse() {
      const vm = this
      const params = {
        type: 4,
        page: 1,
        limit: 1,
        is_active: 1
      }
      vm.$http.get('/warehouse', { params }).then((res) => {
        vm.FBAWarehouses = res.data
      })
    },

    /**
     * change 上级仓库 handler
     * */

    changeWarehouseHandler(parentId) {
      const vm = this
      const selectedWarehouse = vm.warehouseList.find((e) => e.id === parentId)
      vm.formFieldsData.zipcode = selectedWarehouse.zipcode
      vm.formFieldsData.state = selectedWarehouse.state
      vm.formFieldsData.city = selectedWarehouse.city
      vm.formFieldsData.street = selectedWarehouse.street
      vm.formFieldsData.is_third_part = selectedWarehouse.is_third_part
    },
    // 选择所属客户
    changeCompanyHandler(e) {
      const vm = this
      vm.formFieldsData.department_id = ''
      vm.department = []
    },
    /**
     * 选择组织 handler
     * */

    departmentHandler(e) {
      const vm = this
      const departmentId = e.concat().pop()
      vm.formFieldsData.department_id = departmentId
    },
    /**
     * 显示dialog
     * @param {type} 类型-type 0 新增 1 编辑
     * */

    show(editType, item) {
      const vm = this
      vm.getDepartmentList() // 获取组织列表
      vm.getWarehouseList() // 获取上级仓库
      vm.getCompanyList() // 获取所属客户
      vm.getFBAWarehouse() // 获取FBA仓库
      vm.formVisible = true
      vm.type = editType
      if (vm.type === 1) {
        vm.setFormFields(item)
        const selectedState = vm.statesList.find((e) => e.code === vm.formFieldsData.state)
        vm.getCityList(selectedState.id)
        vm.backfillDepartment() // 回填组织
      }
    },

    /**
     * 设置内容
     * */
    setFormFields(form) {
      const vm = this
      for (const key in vm.formFieldsData) {
        const value = form[key]
        if (value) {
          vm.formFieldsData[key] = value
        }
        if (key === 'is_third_part') {
          vm.formFieldsData[key] = value
        }
      }
    },
    /**
     * 清除表单内容
     * */
    clearFormFields() {
      const vm = this
      for (const key in vm.formFieldsData) {
        vm.formFieldsData[key] = ''
      }
    },
    /**
     * 回填组织
     * */
    backfillDepartment() {
      const vm = this
      let returnItem
      const findItem = (arr, id) => {
        for (let i = 0; i < arr.length; i++) {
          const item = arr[i]
          if (item.id === id) {
            returnItem = item
            return
          }
          if (item.children) {
            findItem(item.children, id)
          }
        }
      }
      findItem(vm.departments, vm.formFieldsData.department_id)
      if (returnItem) {
        vm.department = returnItem.ids
      }
    },
    /**
     * 获取城市邮编列表
     * */
    getCityCodeList(id) {
      const vm = this
      cityPostalCode(id).then((res) => {
        vm.cityCodeList = res
      })
    },
    /**
     * 获取街道列表
     * */

    getStreetList(id) {
      const vm = this
      streetList(id).then((res) => {
        vm.streetList = res
      })
    },
    /**
     * 获取城市列表
     * */
    getCityList(id, callback) {
      const vm = this
      cityList(id).then((res) => {
        vm.cityList = res
        if (typeof callback === 'function') {
          callback()
        }
      })
    },
    /**
     * 选择城市 change Handler
     * */

    changeCityHandler(selectedName) {
      const vm = this
      const selectedCity = vm.cityList.find((e) => (e.lower_name === selectedName))
      vm.getStreetList(selectedCity.id) // 获取街道列表
      if (vm.isFirstLevel) {
        vm.formFieldsData.zipcode = '' // 清空城市邮编
        vm.getCityCodeList(selectedCity.id) // 获取城市邮编
      }
    },
    /**
     * 获取省/州列表
     * */

    getStatesList() {
      const vm = this
      statesList().then((res) => {
        vm.statesList = res
      })
    },
    /**
     * 选择省/州change Handler
     * */

    changeStateHandler(selectedName) {
      const vm = this
      const selectedState = vm.statesList.find((e) => e.code === selectedName)
      vm.cityList = []
      vm.cityCodeList = []
      vm.formFieldsData.city = ''
      vm.formFieldsData.zipcode = ''
      vm.getCityList(selectedState.id)
    },

    /**
     * 提交新增仓库表单
     * */

    handleSubmitSelf() {
      const vm = this
      vm.$refs[vm.formName].validate((valid) => {
        if (valid) {
          vm.btnLoading = true
          const params = Object.assign({}, vm.formFieldsData)
          // 实体仓没有上级仓 非实体仓没有所属组织
          if (params.type === 1) {
            params.parent_id = ''
            params.department_id = ''
          }
          vm.type === 0 ? vm.addWarehouse(params) : vm.editWarehouse(params)
        }
      })
    },

    addWarehouse(params) {
      const vm = this
      vm.$http
        .post('/warehouse', params)
        .then((res) => {
          vm.$message.success('添加成功')
          vm.handleCancel()
          vm.btnLoading = false
          vm.$emit('submit')
        })
        .catch(() => {
          vm.btnLoading = false
        })
    },

    editWarehouse(params) {
      const vm = this
      vm.$http
        .put(`/warehouse/${params.id}`, params)
        .then((res) => {
          vm.$message.success('编辑成功')
          vm.handleCancel()
          vm.btnLoading = false
          vm.$emit('submit')
        })
        .catch(() => {
          vm.btnLoading = false
        })
    },

    /**
     * 取消
     * */

    handleCancel() {
      const vm = this
      vm.$refs[vm.formName].resetFields()
      vm.formFieldsData.id = '' // 仓库id
      vm.formFieldsData.name = '' // 仓库名称
      vm.formFieldsData.code = '' // 仓库编码
      vm.formFieldsData.type = '' // 仓库类型
      vm.formFieldsData.parent_id = '' // 上级仓库id
      vm.formFieldsData.department_id = '' // 所属组织
      vm.formFieldsData.state = '' // 省/州
      vm.formFieldsData.city = '' // 城市
      vm.formFieldsData.street = '' // 街道
      vm.formFieldsData.zipcode = '' // 邮编
      vm.formFieldsData.notes = '' // 备注
      vm.formFieldsData.is_third_part = '' // 是否第三方仓库
      vm.formVisible = false
      vm.department = []
    }
  }
}
</script>

<style lang="scss" scoped>
.warehouse_add_dialog {
  .header_title_box {
    margin-bottom: 0;
  }
}
.warehouse_add_dialog ::v-deep .el-dialog__header {
  padding: 16px 16px 24px;
}
.warehouse_add_dialog ::v-deep .el-dialog__body {
  padding: 0 23px 0 16px;
}
.warehouse_add_dialog ::v-deep .el-dialog__footer .el-button + .el-button {
  margin-left: 64px;
}
</style>
